package classes;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

public class Conexao {
    public static Connection getConnection(String user, String pass) throws Exception{
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://54.69.151.234:5432/NutriWeb";
        return DriverManager.getConnection(url, user, pass);
    }

    public static int executeStatement(String SQL, Object... params) throws Exception {
        Exception e = null;
        int result = 0;
        Connection con = null;
        PreparedStatement stmt = null;
        int index = 1;
        try {
            con = getConnection("app", "nutriweb");
            stmt = con.prepareStatement(SQL);
            
            for (Object param : params){
                stmt.setObject(index++, param);
            }

            result = stmt.executeUpdate();
        } catch (Exception ex) {
            e = ex;
        } finally {
            try{stmt.close();}catch(Exception ex2){e = ex2;}
            try{con.close();}catch(Exception ex2){e = ex2;}
        }
        if (e != null) {
            throw e;
        }
        return result;
    }
    
    public static ArrayList<Object[]> getQuery(String SQL) throws Exception {
        Exception e = null;
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        ArrayList<Object[]> result = null;
        try {
            con = getConnection("app","nutriweb");
            stmt = con.createStatement();
            rs = stmt.executeQuery(SQL);
            result = new ArrayList<Object[]>();
            while(rs.next()) {
                Object[] reg = new Object[rs.getMetaData().getColumnCount()];
                for(int i=0; i<rs.getMetaData().getColumnCount();i++)
                    reg[i] = rs.getObject(i+1);
                result.add(reg);
            }
        } catch (Exception ex){
            e = ex;
        } finally {
            if (rs != null){
                try{rs.close();}catch(Exception ex2){e = ex2;}
            }
            try{stmt.close();}catch(Exception ex2){e = ex2;}
            try{con.close();}catch(Exception ex2){e = ex2;}
        }
        if(e!=null) throw e;
        return result;
    }
}

